# encoding=utf-8
"""
响应对象业务校验
"""
import json
import logging

from pyquery import PyQuery
from scrapy.exceptions import IgnoreRequest
from zc_core.middlewares.validate import BaseValidateMiddleware
from zc_core.util.http_util import retry_request
from esgcc.matcher import clean_jsonp


class BizValidator(BaseValidateMiddleware):

    def validate_sku(self, request, response, spider):
        if 300 < response.status < 400:
            spider.logger.info('[Sku]异常重定向：[%s][%s] -> [%s]' % (str(response.status), request.url, request.meta))
            return retry_request(request)
        txt = response.text
        txt = clean_jsonp(txt)
        if txt:
            rs = json.loads(txt)
            if rs and 'success' in rs and rs.get('success'):
                return response
        if txt == '' and request.meta.get('page') == 1:
            meta = request.meta
            raise Exception('分页为空 supplierId:{} startPrice:{} endPrice:{}'.format(meta.get('supplierId'), meta.get('startPrice'),
                                                                                  meta.get('endPrice')))
        else:
            spider.logger.info('[Sku]响应异常：[%s] -> [%s]' % (request.url, request.meta))
            return retry_request(request)

    def validate_item(self, request, response, spider):
        meta = request.meta
        sku_id = meta.get('skuId')
        retry_times = meta.get('validate_retry_times')

        jpy = PyQuery(response.text)
        status = jpy('input#prod_status')
        if not status:
            # 重试：商品不可访问
            spider.logger.error('[Item]不可访问：sku=%s, retry=%s]' % (sku_id, retry_times))
            return retry_request(request)
        else:
            val = str(status.attr("value"))
            if not val:
                # 重试：商品状态未知
                spider.logger.error('[Item]状态未知：[%s]' % sku_id)
                return retry_request(request)
            # '03','04', '02'均为下架
            if val in ['03', '04', '02']:
                raise IgnoreRequest('[Item]商品下架：[%s]' % sku_id)
            elif val in ['05']:
                # 商品正常在售
                return response
            else:
                # 状态含义未知(暂时放行)
                spider.logger.error('=======>[Item]未知含义状态：[%s]->[%s]' % (sku_id, val))
                return response

    def more_validation(self, request, response, spider):
        meta = request.meta
        if meta and 'reqType' in meta:
            type = meta.get('reqType')
            if 'prod_detail' == type:
                return self.validate_prod_detail(request, response, spider)
            if 'order_ios' == type:
                return self.validate_order_ios(request, response, spider)
        # 未匹配响应放行
        return response

    def validate_prod_detail(self, request, response, spider):
        if response.text:
            return response
        # 重试：响应无内容
        spider.logger.info('[ProdDetail]响应无内容：[%s]' % (request.meta.get('skuId')))
        return retry_request(request)

    def validate_order_ios(self, request, response, spider):
        if '未知异常' in response.text:
            spider.logger.info('[OrderIOS]未知异常：[%s] [%s]' % (request.meta.get('skuId'), response.text))
            return retry_request(request)
        return response
